package com.itic.appbase.applications.itext;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletResponse;
/**
 * 采用模板模式导出word，继承该类，重写exportAutoWord方法即可
 * <p>Company: itic</p>
 * @author: shijun
 * @date: 2015年6月17日 下午3:33:50
 * @version: V1.0
 */
public abstract class ExportWord {
    public void exportWord(Map<String,Object> mapConfig,HttpServletResponse response) throws IOException{
        OutputStream  os = null;
        try {
            //清空resonance
            response.reset();
            os = new BufferedOutputStream(response.getOutputStream());
            // 设置下载文件的类型
            response.setContentType("application/msword");
            // 随机生成下载的文件名
            Random random = new Random();
            String newpath = "file" + random.nextInt() + ".doc";
            response.setHeader("Content-Disposition", "attachment;filename=" + newpath);
            response.setCharacterEncoding("utf-8");
            exportAutoWord(mapConfig,os);//导出word
            os.flush();
            os.close();
        } catch (Exception e) {
            String simplename = e.getClass().getSimpleName();
            if(!"ClientAbortException".equals(simplename)){
                throw new RuntimeException();
            }
        }finally{
            if(null!=os){
                os.close();
            }
        }
    }
    /**
     * 导出word的具体实现
     * @param mapConfig
     * @param out
     * @throws IOException 
     */
    protected abstract void exportAutoWord(Map<String,Object> mapConfig,OutputStream out) throws IOException;
}
